package com.qd.panda.org;

import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.ApiResultWrapper;
import com.cdqidi.dto.DelDTO;
import com.cdqidi.util.ValidatorUtil;
import com.cdqidi.valid.group.DefaultGroup;
import com.cdqidi.valid.group.UpdateGroup;
import com.qd.common.panda.domain.entity.org.OrgAgentDTO;
import com.qd.common.sys.annotation.OperatorInfo;
import com.qd.common.sys.enums.OperatorType;
import com.qd.panda.service.org.OrgAgentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.time.LocalDateTime;
import java.util.List;

/**
 * WEB_代理商
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/sys/orgAgent/")
@Slf4j
public class OrgAgentController {
    private final OrgAgentService orgAgentService;
    private final ValidatorUtil validatorUtil;

    /**
     * 添加修改代理商
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @PostMapping(value = "/save")
    @PreAuthorize("@ps.hasPermission('system:orgAgent:save')")
    @OperatorInfo(title = "添加修改代理商信息", operator = OperatorType.INSERT)
    public OrgAgentDTO save(@Validated({DefaultGroup.class}) @RequestBody OrgAgentDTO dto) {
        if (StringUtils.hasLength(dto.getOrgId())) {
            dto.setUpdateTime(LocalDateTime.now());
            validatorUtil.checkValid(dto, UpdateGroup.class, DefaultGroup.class);
            return orgAgentService.update(dto);
        } else {
            validatorUtil.checkValid(dto, DefaultGroup.class);
            dto.setAddTime(LocalDateTime.now());
            return orgAgentService.save(dto);
        }
    }

    /**
     * 删除代理商
     *
     * @param delDTO 主键，多个用分号隔开
     * @return 页面对象
     */
    @DeleteMapping(value = "/delete")
    @PreAuthorize("@ps.hasPermission('system:orgAgent:update')")
    @OperatorInfo(title = "删除代理商信息", operator = OperatorType.DELETE)
    public ApiResultWrapper<Object> delete(@Validated @RequestBody DelDTO<String> delDTO) {
        List<String> ids = delDTO.getIds();
        if (ids.size() == 1) {
            orgAgentService.removeById(ids.get(0));
        } else {
            orgAgentService.removeBatchIds(ids);
        }
        return ApiResult.success("删除成功");
    }

    /**
     * 获取代理商
     *
     * @param id 主键
     * @return 记录
     */
    @GetMapping(value = "/getById")
    public ApiResultWrapper<Object> getById(@Validated @NotBlank(message = DelDTO.ID_NULL_MSG) String id) {
        OrgAgentDTO agentDTO = orgAgentService.getByIdDto(id);
        if (null == agentDTO) {
            return ApiResult.error(ApiResultWrapper.NULL_ERROR, "数据为空");
        }
        return ApiResult.success(agentDTO);
    }
}